<?php
/**
* DBFactory.php file
* create by ljanson
* @2013-3-4
*/
class DBFactory{
	private $_pdo = null;
	static $_instance;
	
	private function __construct($type) {
		if($type == "YouPin" || $type == "YouPinKu" || $type == "YouPinMZ"){
			switch($type){
				case "YouPin": 
					$InitData = array("host"=>"1.2.90.84", "port"=>"20000", "dbname"=>"youpin", "username"=>"root", "pwd"=>"RQY@n22hu1");
					break;
				case "YouPinKu":
					$InitData = array("host"=>"1.4.6.184", "port"=>"1025", "dbname"=>"YouPinKu", "username"=>"root", "pwd"=>"lgfz100689223");
					break;
				case "YouPinMZ":
					$InitData = array("host"=>"1.4.6.192", "port"=>"1025", "dbname"=>"ypmz", "username"=>"root", "pwd"=>"06BCMOYf5aiX");
					break;
			}
			
			try {
				$dns = "mysql:host={$InitData["host"]};port={$InitData["port"]};dbname={$InitData["dbname"]}";
				$this->_pdo = new PDO($dns, $InitData["username"], $InitData["pwd"], array(PDO::MYSQL_ATTR_INIT_COMMAND=>'SET NAMES UTF8'));
				$this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			} catch (PDOException $e) {
				exit($e->getMessage());
			}
		}
		else{
			exit("数据库选择错误！");
		}
	}
	
	private function __clone(){}
	
	public static function getInstance($type){
		if( ! (self::$_instance instanceof self) ){
			self::$_instance = new self($type);
		}
		return self::$_instance;
	}
	
	//验证一条数据是否存在
	public function isOne($_table, $_field, Array $_param) {
		$_where = '';
		foreach ($_param as $_value) {
			$_where .=$_value.' AND ';
		}
		$_where = 'WHERE '.substr($_where, 0, -4);
		$_sql = "SELECT $_field FROM $_table $_where LIMIT 1";

		return $this->execute($_sql)->rowCount();
	}
	
	//执行SQL，返回true,false
	public function DoExecute($_sql) {
		try {
			$_stmt = $this->_pdo->prepare($_sql);
			$res = $_stmt->execute();
		} catch (PDOException  $e) {
			exit('SQL语句：'.$_sql.'<br />错误信息：'.$e->getMessage());
		}
		return $res;
	}
	
	//执行SQL，返回statement
	public function execute($_sql) {
		try {
			$_stmt = $this->_pdo->prepare($_sql);
			$_stmt->execute();
		} catch (PDOException  $e) {
			exit('SQL语句：'.$_sql.'<br />错误信息：'.$e->getMessage());
		}
		return $_stmt;
	}
}